import { colors } from '../modules.js'

// 创建 Raycaster 和鼠标 Vector2
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();


export const regHover = (camera, scene, cubes) => {

    const onMouseMove = (event) => {
        // 将鼠标位置归一化到 -1 到 1 之间（适用于 Three.js）
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // 通过 Raycaster 投射一条射线
        raycaster.setFromCamera(mouse, camera);

        // 检查与哪些对象相交
        const intersects = raycaster.intersectObjects(scene.children);

        cubes.forEach(cube => {
            let type = cube.userData.type
            cube.material.color.set(colors[type]);  // 先将所有物体颜色重置原始色
        });

        // 如果射线与对象相交，改变对象的颜色
        if (intersects.length > 0) {
            const element = intersects[0]
            const userData = element.object.userData
            if (userData.type) {
                let type = userData.type
                element.object.material.color.set(colors[`${type}hl`]);  // 
            } else {
            }

        } else {
        }
    }

    // 监听鼠标移动事件
    window.addEventListener('mousemove', onMouseMove, false);
}

export const regClick = (camera, scene, cubes) => {
    // 监听鼠标点击事件
    function onMouseClick(event) {
        // 将鼠标坐标转换为标准化设备坐标 (NDC)
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // 通过 Raycaster 检测物体
        raycaster.setFromCamera(mouse, camera);
        const intersects = raycaster.intersectObjects(scene.children);

        if (intersects.length > 0) {
            const element = intersects[0]
            const userData = element.object.userData
            if (userData.type) {
                // 显示提示文本并更新位置
                tooltip.style.display = 'block';
                tooltip.style.left = `${event.clientX + 10}px`;  // 将提示框移动到鼠标位置
                tooltip.style.top = `${event.clientY + 10}px`;
                let str = userData.xx + '\n';
                const points = userData.points;
                str += JSON.stringify(points).replace(/},/g, '},\n');
                tooltip.textContent = str;  // 显示物体的名字
            } else {
                tooltip.style.display = 'none';
            }

        } else {
            tooltip.style.display = 'none';
        }
    }

    // 监听鼠标点击事件
    window.addEventListener('click', onMouseClick, false);
}